﻿import game.Actor;
import game.Main;
class game.SandClock extends Actor{

	private var _sand:Number;
	function get Sand():Number{return _sand;}
	function set Sand(val:Number){_sand = val;}

	private var _firstFill:Number;
	function get FirstFill():Number{return _firstFill;}
	function set FirstFill(val:Number){_firstFill = val>>0;}

	function get consumeRatio():Number{return _sand/_firstFill;}

	function get isEmpty():Boolean{return _sand <= 0;}

	private var _standalone:Boolean;
	
	static function create(firstFill:Number, func:Function):Void{
		var s:SandClock = new SandClock(firstFill, func);
	}

	function SandClock(firstFill:Number, func:Function){
		_firstFill	= firstFill>>0;// (floor)
		_sand		= 0;
		
		if (func != null){
			_standalone		= true;
			Main.getInstance().addToLoop(this);
			this.onEmptied = func;
			this.onRemoved = removed;
			flip();
		}

	}
	
	private function removed():Void {
	 Main.getInstance().removeFromLoop(this);
	}

	function update() {
		
		consume();
	}
	
	function get isWorking():Boolean{
		return _sand>0;
	}

	function fill(sand:Number){
		_firstFill	= sand;
		_sand		= _firstFill;
	}

	function fillAndFlip(sand:Number){
		fill(sand);
		flip();
	}

	function empty(){
		_sand		= 0;
	}

	function flip(){
		_sand		= _firstFill;
	}

	function onEmptied(){} // event
	function onConsuming(){} // event

	function consume(){
		if (_sand > 0){
			_sand --;

			if (_sand <= 0){
				onEmptied();
				if (_standalone){remove();}
			}else{
				onConsuming();
			}
		}else{
			_sand = 0;
		}
	}
}